Python 24일 코스 - Day 14: 상속과 다형성

Day 14: 상속과 다형성

기본 상속

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("하위 클래스에서 구현하세요")

class Dog(Animal):
    def speak(self):
        return f"{self.name}: 멍멍!"

class Cat(Animal):
    def speak(self):
        return f"{self.name}: 야옹!"

dog = Dog("바둑이")
cat = Cat("나비")
print(dog.speak())  # 바둑이: 멍멍!
print(cat.speak())  # 나비: 야옹!

super()로 부모 호출

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def info(self):
        return f"{self.name}, 연봉: {self.salary}만원"

class Manager(Employee):
    def __init__(self, name, salary, department):
        super().__init__(name, salary)
        self.department = department

    def info(self):
        base = super().info()
        return f"{base}, 부서: {self.department}"

mgr = Manager("김부장", 8000, "개발팀")
print(mgr.info())  # 김부장, 연봉: 8000만원, 부서: 개발팀

다형성

class Shape:
    def area(self):
        raise NotImplementedError

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return 3.14159 * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height

# 다형성: 같은 인터페이스, 다른 동작
shapes = [Circle(5), Rectangle(4, 6), Circle(3)]
for shape in shapes:
    print(f"넓이: {shape.area():.2f}")

isinstance와 issubclass

print(isinstance(dog, Dog))      # True
print(isinstance(dog, Animal))   # True
print(issubclass(Dog, Animal))   # True
print(issubclass(Dog, Cat))      # False

오늘의 연습문제

  1. Vehicle 기본 클래스와 Car, Bicycle, Truck 하위 클래스를 만드세요.
  2. 도형 상속 구조를 만들고, 여러 도형의 전체 넓이 합계를 구하세요.
  3. Payment 기본 클래스로 CardPayment, CashPayment 등을 구현하세요.

이 글이 도움이 되었나요?